<template>
  <div id="main">
    <a-form :form="form">
      <a-form-item class="mb10" label="数据类型" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
        <input
          v-decorator="['username', {rules: [{ required: true, message: '用户名' }]}]"
          placeholder/>
        <button @click="get">get</button>
        <p>{{ username }}</p>
        <p>{{ getMessage }}</p>
        <br/>
      </a-form-item>
    </a-form>
    message: <input v-model="msg"/>
    <button @click="send">发消息</button>
    <br/>
    <p>{{ data }}</p>
    <button @click="go">go</button>
  </div>
</template>

<script>
import { axios } from '../../utils/request'

export default {
  data () {
    return {
      formLayout: 'horizontal',
      form: this.$form.createForm(this),
      msg: '',
      data: null,
      path: 'ws://localhost:8080/socket/1',
      socket: null,
      username: ''
    }
  },
  mounted () {
    console.log('go in mounted')
    console.log('form', this.$form)
    // this.setValue()
    this.init()
  },
  methods: {
    get () {
      alert(this.form.getFieldValue('username'))
    },
    // setValue () {
    //   console.log('this.form', this.form)
    //   this.form.setFieldsValue({
    //     'username': this.username
    //   })
    //   console.log(this.form.getFieldsValue(['username']))
    // },
    init: function () {
      if (typeof (WebSocket) === 'undefined') {
        alert('您的浏览器不支持socket')
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function () {
      console.log('socket连接成功')
    },
    error: function () {
      console.log('连接错误')
    },
    getMessage: function (msg) {
      this.data = msg.data
      console.log('get a message:', msg.data)
    },
    send: function () {
      this.socket.send(this.msg)
    },
    close: function () {
      console.log('socket已经关闭')
    },
    go () {
      axios({
        url: '/test',
        method: 'get'
      })
    }
  },
  destroyed () {
    // 销毁监听
    this.socket.onclose = this.close
  }
}
</script>
